//
//  WalletsViewController.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 9/13/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "WalletsViewController.h"
#import "DataBaseAccess.h"
#import "WalletCell.h"

#define kRowHeight 70

@implementation WalletsViewController

@synthesize table;
@synthesize walletsList;
@synthesize manageWalletView;
//@synthesize delegate;
@synthesize popupView;
@synthesize addWalletView;
@synthesize editButton;
@synthesize deleteButton;
@synthesize btnEdit;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //=======================Notification Center ===================//
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadTableView :) name:@"reloadTableView" object:nil];
    
}

- (void)viewDidUnload {
    [self setManageWalletView:nil];
    [self setAddWalletView:nil];
    [self setPopupView:nil];
    [self setEditButton:nil];
    [self setDeleteButton:nil];

  //  [super viewDidUnload];
    table           = nil;
    walletsList     = nil;
   // delegate        = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    if([walletsList count] !=0) {
        [walletsList removeAllObjects];
    }
    walletsList = [[NSMutableArray alloc] initWithArray:[DataBaseAccess getAllWallet]
                   ];  
    [table reloadData];
    [super viewWillAppear:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - TableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [walletsList count];
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRowHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WalletIdentifier = @"WalletIdentifier";
    
    WalletCell *cell = (WalletCell *)[tableView dequeueReusableCellWithIdentifier:WalletIdentifier];
  
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    Wallet *tempWallet = [walletsList objectAtIndex:indexPath.row];
    
    if(cell == nil)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"WalletCell" owner:nil options:nil] objectAtIndex:0];
        
        [cell addGestureRecognizer:longTap];
        
    }
    cell.imvLogo.image = [UIImage imageNamed:tempWallet.w_image];
    if(tempWallet.w_isLocked.boolValue) {
        cell.imvLock.image = [UIImage imageNamed:@"lock2.png"]; 
    }
    else {
        cell.imvLock.image = [UIImage imageNamed:@"unlock.png"];
    }
       
    
    cell.lbName.text = [[walletsList objectAtIndex:indexPath.row] w_name];
    
    Currency *symbol = [tempWallet wToCurrency];
    NSLog(@"SYMBOL = %@", [symbol valueForKey:kCurrencyName]);
    cell.lbBalance.text = [NSString stringWithFormat:@"%@", tempWallet.w_balance];
    cell.lbCurrency.text = [NSString stringWithFormat:@"%@",tempWallet.wToCurrency.c_symbol];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.currentWallet = [walletsList objectAtIndex:indexPath.row];

    gTabBarController = [[UITabBarController alloc]init];
    NSMutableArray *controllers = [[NSMutableArray alloc]init];
    
    GeneralManagerViewController *gmvc = [[GeneralManagerViewController alloc] initWithNibName:@"GeneralManagerViewController" bundle:nil];
    gmvc.tabBarItem.image = [UIImage imageNamed:@"money-01.png"];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:gmvc];
    [nav1 setNavigationBarHidden:YES];
    [controllers addObject:nav1];
    
    ReportViewController *rvc = [[ReportViewController alloc] initWithNibName:@"ReportViewController" bundle:nil];
    rvc.tabBarItem.image = [UIImage imageNamed:@"chart-01.png"];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:rvc];
    [nav2 setNavigationBarHidden:YES];
    [controllers addObject:nav2];
    
    PlanViewController *pvc = [[PlanViewController alloc] initWithNibName:@"PlanViewController" bundle:nil];
    pvc.tabBarItem.image = [UIImage imageNamed:@"save-01.png"];
    UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:pvc];
    [nav3 setNavigationBarHidden:YES];
    [controllers addObject:nav3];
    
    ToolsViewController *tvc = [[ToolsViewController alloc] initWithNibName:@"ToolsViewController" bundle:nil];
    tvc.tabBarItem.image = [UIImage imageNamed:@"tool-01.png"];
    UINavigationController *nav4 = [[UINavigationController alloc] initWithRootViewController:tvc];
    [nav4 setNavigationBarHidden:YES];
    [controllers addObject:nav4];
    
    SettingsViewController *svc = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
    svc.tabBarItem.image = [UIImage imageNamed:@"settings-01.png"];
    UINavigationController *nav5 = [[UINavigationController alloc] initWithRootViewController:svc];
    [nav5 setNavigationBarHidden:YES];
    [controllers addObject:nav5];
    
    gTabBarController.viewControllers = controllers;
    gTabBarController.customizableViewControllers = controllers;
    [gTabBarController setSelectedViewController:nav1];
    gTabBarController.delegate = self;
    
    gTabBarController.selectedIndex = 0;
    
    if(delegate.currentWallet.w_isLocked.boolValue) {
        alert = [[BBAlertView alloc]initWithTitle:@" Please Fill Your Password" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        tbfPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 43, 255, 20)];
        [tbfPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        [tbfPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
        tbfPassword.placeholder = @"Password";
        tbfPassword.layer.backgroundColor =[UIColor whiteColor].CGColor;
        [  tbfPassword setFont:[UIFont boldSystemFontOfSize:14]];
        [alert addSubview:tbfPassword];
        
        
        
        UIButton *okeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        okeButton.frame = CGRectMake(10, 80, 128, 43);
        okeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [okeButton setTitle:@"Validate" forState:UIControlStateNormal];
        
        [okeButton addTarget:self action:@selector(validatePassword) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:okeButton];
        
                
     
        
        UIButton *cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.frame = CGRectMake(145, 80, 128, 43);
        cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelUnlock) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:cancelButton];
        
        [alert show];
    } else {
        [self.navigationController pushViewController:gTabBarController animated:YES];
    }
    
   // [self.delegate walletDidSelected:[walletsList objectAtIndex:indexPath.row]];
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Wallet *wallet = [walletsList objectAtIndex:indexPath.row];
    [DataBaseAccess deleteWallet:wallet];
    [walletsList removeObject:wallet];
    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - IBAction


-(IBAction)addWallet:(id)sender
{
    AddWalletViewController *addWallerViewController = [[AddWalletViewController alloc]init];
    addWallerViewController.viewKind = @"Add";
    [self.navigationController pushViewController:addWallerViewController animated:YES];
    
}

- (IBAction)editButtonClicked:(id)sender {
    [popup dismissModal];
    if(currentWallet.w_isLocked.boolValue) {
        alert = [[BBAlertView alloc]initWithTitle:@" Please Fill Your Password" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        tbfPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 43, 255, 20)];
        [tbfPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        [tbfPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
        tbfPassword.placeholder = @"Password";
        tbfPassword.layer.backgroundColor =[UIColor whiteColor].CGColor;
        [  tbfPassword setFont:[UIFont boldSystemFontOfSize:14]];
        [alert addSubview:tbfPassword];
        
        
        
        UIButton *okeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        okeButton.frame = CGRectMake(10, 80, 128, 43);
        okeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [okeButton setTitle:@"Validate" forState:UIControlStateNormal];
        
        [okeButton addTarget:self action:@selector(validatePasswordOnEdit) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:okeButton];
        
        
        
        
        UIButton *cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.frame = CGRectMake(145, 80, 128, 43);
        cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelUnlock) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:cancelButton];
        
        [alert show];
    } else {
        AddWalletViewController *editViewController = [[AddWalletViewController alloc]init];
        editViewController.viewKind = @"Edit";
        editViewController.currentWallet = currentWallet;
        [self.navigationController pushViewController:editViewController animated:YES];
        [popup dismissModal];
    }
    
}

- (IBAction)deleteButtonClicked:(id)sender {
    [popup dismissModal];
    if(currentWallet.w_isLocked.boolValue) {
        alert = [[BBAlertView alloc]initWithTitle:@" Please Fill Your Password" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        tbfPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 43, 255, 20)];
        [tbfPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        [tbfPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
        tbfPassword.placeholder = @"Password";
        tbfPassword.layer.backgroundColor =[UIColor whiteColor].CGColor;
        [  tbfPassword setFont:[UIFont boldSystemFontOfSize:14]];
        [alert addSubview:tbfPassword];
        
        
        
        UIButton *okeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        okeButton.frame = CGRectMake(10, 80, 128, 43);
        okeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [okeButton setTitle:@"Validate" forState:UIControlStateNormal];
        
        [okeButton addTarget:self action:@selector(validatePasswordOnDelete) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:okeButton];
        
        
        
        
        UIButton *cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.frame = CGRectMake(145, 80, 128, 43);
        cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelUnlock) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:cancelButton];
        
        [alert show];
    } else {
        
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [DataBaseAccess deleteWallet:currentWallet];
        [walletsList removeObject:currentWallet];
        [popup dismissModal];
        [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:myIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
}

- (IBAction)viewButtonClicked:(id)sender {
    [popup dismissModal];
    if(currentWallet.w_isLocked.boolValue) {
        alert = [[BBAlertView alloc]initWithTitle:@" Please Fill Your Password" message:@"\n\n\n" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        
        tbfPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 43, 255, 20)];
        [tbfPassword setClearButtonMode:UITextFieldViewModeWhileEditing];
        [tbfPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
        tbfPassword.placeholder = @"Password";
        tbfPassword.layer.backgroundColor =[UIColor whiteColor].CGColor;
        [  tbfPassword setFont:[UIFont boldSystemFontOfSize:14]];
        [alert addSubview:tbfPassword];
        
        
        
        UIButton *okeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        okeButton.frame = CGRectMake(10, 80, 128, 43);
        okeButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [okeButton setTitle:@"Validate" forState:UIControlStateNormal];
        
        [okeButton addTarget:self action:@selector(validatePasswordOnView) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:okeButton];
        
        
        
        
        UIButton *cancelButton =[UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.frame = CGRectMake(145, 80, 128, 43);
        cancelButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"PopUp_Button_Half.png"]];
        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelUnlock) forControlEvents:UIControlEventTouchUpInside];
        [alert addSubview:cancelButton];
        
        [alert show];
    } else {
        ViewWalletController *viewWalletController = [[ViewWalletController alloc]init];
        viewWalletController.currentWallet = currentWallet;
        [self.navigationController pushViewController:viewWalletController animated:YES];
        [popup dismissModal];
    }
   
}

-(void)validatePassword{
    folyAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    if([tbfPassword.text isEqualToString: delegate.currentWallet.w_pword]) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [self.navigationController pushViewController:gTabBarController animated:YES];
    }else {
       tbfPassword.text =@"";
       tbfPassword.placeholder = @"Wrong Password";
        [tbfPassword resignFirstResponder];
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration];
        tbfPassword.layer.borderWidth =2 ;
        tbfPassword.layer.borderColor = [UIColor redColor].CGColor;
        [CATransaction commit];
    }
}

-(void) validatePasswordOnDelete {
        if([tbfPassword.text isEqualToString: currentWallet.w_pword]) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [DataBaseAccess deleteWallet:currentWallet];
        [walletsList removeObject:currentWallet];
        [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:myIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }else {
        tbfPassword.text =@"";
        tbfPassword.placeholder = @"Wrong Password";
        [tbfPassword resignFirstResponder];
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration];
        tbfPassword.layer.borderWidth =2 ;
        tbfPassword.layer.borderColor = [UIColor redColor].CGColor;
        [CATransaction commit];
    }

}

-(void) validatePasswordOnEdit {
    if([tbfPassword.text isEqualToString: currentWallet.w_pword]) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        AddWalletViewController *editViewController = [[AddWalletViewController alloc]init];
        editViewController.viewKind = @"Edit";
        editViewController.currentWallet = currentWallet;
        [self.navigationController pushViewController:editViewController animated:YES];
    }else {
        tbfPassword.text =@"";
        tbfPassword.placeholder = @"Wrong Password";
        [tbfPassword resignFirstResponder];
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration];
        tbfPassword.layer.borderWidth =2 ;
        tbfPassword.layer.borderColor = [UIColor redColor].CGColor;
        [CATransaction commit];
    }

}

-(void)validatePasswordOnView {
    if([tbfPassword.text isEqualToString: currentWallet.w_pword]) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        ViewWalletController *viewWalletController = [[ViewWalletController alloc]init];
        viewWalletController.currentWallet = currentWallet;
        [self.navigationController pushViewController:viewWalletController animated:YES];
    }else {
        tbfPassword.text =@"";
        tbfPassword.placeholder = @"Wrong Password";
        [tbfPassword resignFirstResponder];
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration];
        tbfPassword.layer.borderWidth =2 ;
        tbfPassword.layer.borderColor = [UIColor redColor].CGColor;
        [CATransaction commit];
    }
    
   
}
-(void)cancelUnlock {
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}
#pragma mark - UIGesture Delegate

-(void) handleLongPress: (UIGestureRecognizer *)longPress {
    CGRect rectOfCellInTableView;
    CGRect rectOfCellInSuperview;
    
    CGPoint p = [longPress locationInView:self.table];
    
    NSIndexPath *indexPath = [self.table indexPathForRowAtPoint:p];
    myIndexPath = indexPath;
    
    rectOfCellInTableView = [self.table rectForRowAtIndexPath:indexPath];
    rectOfCellInSuperview = [self.table convertRect:rectOfCellInTableView toView:[self.table superview]];
    
    currentWallet = [walletsList objectAtIndex:indexPath.row];
//    if (indexPath == nil)
//        NSLog(@"long press on table view but not on a row");
//    else
//        NSLog(@"long press on table view at row %d", indexPath.row);
//    
//    CGRect currentRowFrame = CGRectMake(0, 0, 320, kRowHeight);
//    currentRowFrame.origin.y = kRowHeight * (indexPath.row +1) +30;
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popupView contentSize:CGSizeMake(217, 67)];
		
        [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50)  inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}


}

#pragma mark - PopUp Delegate

- (void)didTouchPopupView:(SNPopupView*)sender {
//	DNSLogMethod
//	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}

#pragma mark - Reload Table View
- (void) reloadTableView :(NSNotification *)notification {
    [walletsList removeAllObjects];
    walletsList = [NSMutableArray arrayWithArray: [DataBaseAccess getAllWallet]];
    [table reloadData];
}

#pragma mark -------------Tabbar Delegate-------
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if(gTabBarController.selectedIndex == 0){
        folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//        delegate.isDBRefresh = YES;
//        [delegate managedObjectContext];
//        [delegate persistentStoreCoordinator];
//      
//        [delegate managedObjectModel];
       
        [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadIncomeExpenseFromDetail" object:nil];
         [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadLoanDebtFromDetail" object:nil];
    }
    
}
@end
